<template>
  <view class="chat-container">
    <!-- 自定义Header -->
    <CustomHeader></CustomHeader>
    <view class="chat-header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">{{ chatUserName || "聊天" }}</text>
        <view class="header-right">
          <!-- 可以放置更多按钮，暂时留空 -->
        </view>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="message-area" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoView"
      scroll-with-animation
    >
      <!-- 消息列表 -->
      <view class="message-list">
        <view 
          class="message-item"
          v-for="message in messageList"
          :key="message.id"
        >
          <!-- 对方消息 -->
          <view v-if="!isMyMessage(message)" class="message-wrapper">
            <!-- 职位卡片消息特殊布局 -->
            <view v-if="message.msgType === 16" class="job-card-message-wrapper">
              <text class="job-card-tip">当前沟通的职位</text>
              <text class="message-time">{{ formatMessageTime(message.createTime) }}</text>
              <view class="job-card" @click="goToJobDetail(message.content.jobId)">
                <view class="job-header">
                  <text class="job-name">{{ message.content.jobName }}</text>
                  <text class="job-salary">{{ formatSalary(message.content) }}</text>
                </view>
                
                <!-- 企业信息 -->
                <view class="company-info">
                  <text class="company-name">{{ message.content.companyName }}</text>
                  <text class="separator">·</text>
                  <text class="company-detail">{{ message.content.financStage }}</text>
                  <text class="separator">·</text>
                  <text class="company-detail">{{ formatPeopleSize(message.content.peopleSize) }}</text>
                </view>
                
                <!-- 岗位性质 -->
                <view class="job-nature">
                  <text class="nature-tag" v-if="message.content.edu">{{ message.content.edu }}</text>
                  <text class="nature-tag" v-if="message.content.expYears">{{ message.content.expYears }}</text>
                  <text class="nature-tag" v-if="message.content.monthlySalary">{{ message.content.monthlySalary }}薪</text>
                </view>
                
                <!-- 标签 -->
                <view class="job-tags" v-if="message.content.tags">
                  <text
                    class="job-tag"
                    v-for="tag in getTopTags(message.content.tags, 5)"
                    :key="tag"
                  >{{ tag }}</text>
                </view>
                
                <!-- HR信息和地址 -->
                <view class="job-footer">
                  <view class="hr-info">
                    <image
                      :src="message.content.face || '/static/images/avatar.png'"
                      class="hr-avatar"
                    ></image>
                    <view class="hr-text">
                      <text class="hr-name">{{ message.content.name || "HR" }}</text>
                      <text class="hr-position">· {{ message.content.position || "" }}</text>
                    </view>
                  </view>
                  <text class="job-city">{{ message.content.city }}</text>
                </view>
              </view>
            </view>
            <!-- 其他消息类型保持原布局 -->
            <template v-else>
              <image 
                class="avatar" 
                :src="'/static/images/avatar.png'"
              />
              <view class="message-content ">
                <!-- 文本消息 -->
                <view v-if="message.msgType === 10" class="message-bubble message-bubble-left">
                  <text class="message-text">{{ message.content.text }}</text>
                </view>
                <!-- 图片消息 -->
                <view v-else-if="message.msgType === 11" class="image-message-wrapper">
                  <image 
                    class="message-image" 
                    :src="message.content.imageUrl"
                    :style="{ width: message.content.width + 'rpx', height: message.content.height + 'rpx' }"
                    @click="previewImage(message.content.imageUrl)"
                    mode="aspectFit"
                  />
                </view>
                <!-- 语音消息 -->
                <view v-else-if="message.msgType === 12" class="voice-message-wrapper">
                  <view class="message-bubble message-bubble-left voice-message">
                    <view class="voice-content">
                      <image class="voice-icon" src="/static/icons/chat/voice.png" />
                      <text class="voice-duration">{{ message.content.duration }}"</text>
                    </view>
                  </view>
                  <image 
                    v-if="!message.content.isRead" 
                    class="unread-dot-outside" 
                    src="/static/icons/chat/unread_voice.png" 
                  />
                </view>
                <!-- 简历附件消息 -->
                <view v-else-if="message.msgType === 17" class="resume-message-wrapper">
                  <view class="resume-attachment" @click="previewResume(message.content)">
                    <image class="resume-icon" :src="getResumeIcon(message.content.fileType)"></image>
                    <view class="resume-details">
                      <text class="resume-name">{{ message.content.fileName }}</text>
                      <text class="resume-size">{{ formatResumeSize(message.content.fileSizeMb) }}</text>
                    </view>
                  </view>
                </view>
                <!-- 面试邀请消息 -->
                <view v-else-if="message.msgType === 14" class="interview-message-wrapper">
                  <view class="interview-card" @click="viewInterviewDetail(message.content.interviewId)">
                    <view class="interview-header">
                      <image class="interview-icon" src="/static/icons/chat/interview.png"></image>
                      <text class="interview-title">面试邀请</text>
                    </view>
                    <text class="interview-desc">对方要求您进行面试</text>
                    <view class="interview-action">
                      <text class="action-text">点击查看详情</text>
                      <image class="action-arrow" src="/static/icons/right-arrow-gray.png"></image>
                    </view>
                  </view>
                </view>
                <!-- 在线简历消息 -->
                <view v-else-if="message.msgType === 18" class="online-resume-message-wrapper">
                  <view class="online-resume-card" @click="viewOnlineResume(message)">
                    <view class="online-resume-header">
                      <image class="online-resume-icon" src="/static/icons/chat/resume_send.png"></image>
                      <text class="online-resume-title">在线简历</text>
                    </view>
                    <text class="online-resume-desc">点击查看简历详情</text>
                    <view class="online-resume-action">
                      <text class="action-text">查看简历</text>
                      <image class="action-arrow" src="/static/icons/right-arrow-gray.png"></image>
                    </view>
                  </view>
                </view>
                <text class="message-time">{{ formatMessageTime(message.createTime) }}</text>
              </view>
            </template>
          </view>

          <!-- 我的消息 -->
          <view v-else class="message-wrapper message-right">
            <!-- 职位卡片消息特殊布局 -->
            <view v-if="message.msgType === 16" class="job-card-message-wrapper">
              <text class="job-card-tip">当前沟通的职位</text>
              <text class="message-time">{{ formatMessageTime(message.createTime) }}</text>
              <view class="job-card" @click="goToJobDetail(message.content.jobId)">
                <view class="job-header">
                  <text class="job-name">{{ message.content.jobName }}</text>
                  <text class="job-salary">{{ formatSalary(message.content) }}</text>
                </view>
                
                <!-- 企业信息 -->
                <view class="company-info">
                  <text class="company-name">{{ message.content.companyName }}</text>
                  <text class="separator">·</text>
                  <text class="company-detail">{{ message.content.financStage }}</text>
                  <text class="separator">·</text>
                  <text class="company-detail">{{ formatPeopleSize(message.content.peopleSize) }}</text>
                </view>
                
                <!-- 岗位性质 -->
                <view class="job-nature">
                  <text class="nature-tag" v-if="message.content.edu">{{ message.content.edu }}</text>
                  <text class="nature-tag" v-if="message.content.expYears">{{ message.content.expYears }}</text>
                  <text class="nature-tag" v-if="message.content.monthlySalary">{{ message.content.monthlySalary }}薪</text>
                </view>
                
                <!-- 标签 -->
                <view class="job-tags" v-if="message.content.tags">
                  <text
                    class="job-tag"
                    v-for="tag in getTopTags(message.content.tags, 5)"
                    :key="tag"
                  >{{ tag }}</text>
                </view>
                
                <!-- HR信息和地址 -->
                <view class="job-footer">
                  <view class="hr-info">
                    <image
                      :src="message.content.face || '/static/images/avatar.png'"
                      class="hr-avatar"
                    ></image>
                    <view class="hr-text">
                      <text class="hr-name">{{ message.content.name || "HR" }}</text>
                      <text class="hr-position">· {{ message.content.position || "" }}</text>
                    </view>
                  </view>
                  <text class="job-city">{{ message.content.city }}</text>
                </view>
              </view>
            </view>
            <!-- 其他消息类型保持原布局 -->
            <template v-else>
              <view class="message-content">
                <!-- 文本消息 -->
                <view v-if="message.msgType === 10" class="message-bubble message-bubble-right">
                  <text class="message-text">{{ message.content.text }}</text>
                </view>
                <!-- 图片消息 -->
                <view v-else-if="message.msgType === 11" class="image-message-wrapper image-message-wrapper-right">
                  <image 
                    class="message-image" 
                    :src="message.content.imageUrl"
                    :style="{ width: message.content.width + 'rpx', height: message.content.height + 'rpx' }"
                    @click="previewImage(message.content.imageUrl)"
                    mode="aspectFit"
                  />
                </view>
                <!-- 语音消息 -->
                <view v-else-if="message.msgType === 12" class="voice-message-wrapper voice-message-wrapper-right">
                  <image 
                    v-if="!message.content.isRead" 
                    class="unread-dot-outside" 
                    src="/static/icons/chat/unread_voice.png" 
                  />
                  <view class="message-bubble message-bubble-right voice-message">
                    <view class="voice-content voice-content-right">
                      <text class="voice-duration">{{ message.content.duration }}"</text>
                      <image class="voice-icon" src="/static/icons/chat/voice_right.png" />
                    </view>
                  </view>
                </view>
                <!-- 简历附件消息 -->
                <view v-else-if="message.msgType === 17" class="resume-message-wrapper resume-message-wrapper-right">
                  <view class="resume-attachment" @click="previewResume(message.content)">
                    <image class="resume-icon" :src="getResumeIcon(message.content.fileType)"></image>
                    <view class="resume-details">
                      <text class="resume-name">{{ message.content.fileName }}</text>
                      <text class="resume-size">{{ formatResumeSize(message.content.fileSizeMb) }}</text>
                    </view>
                  </view>
                </view>
                <!-- 面试邀请消息 -->
                <view v-else-if="message.msgType === 14" class="interview-message-wrapper interview-message-wrapper-right">
                  <view class="interview-card" @click="viewInterviewDetail(message.content.interviewId)">
                    <view class="interview-header">
                      <image class="interview-icon" src="/static/icons/chat/interview.png"></image>
                      <text class="interview-title">面试邀请</text>
                    </view>
                    <text class="interview-desc">您邀请了对方进行面试</text>
                    <view class="interview-action">
                      <text class="action-text">点击查看详情</text>
                      <image class="action-arrow" src="/static/icons/right-arrow-gray.png"></image>
                    </view>
                  </view>
                </view>
                <!-- 在线简历消息 -->
                <view v-else-if="message.msgType === 18" class="online-resume-message-wrapper online-resume-message-wrapper-right">
                  <view class="online-resume-card" @click="viewOnlineResume(message)">
                    <view class="online-resume-header">
                      <image class="online-resume-icon" src="/static/icons/chat/resume_send.png"></image>
                      <text class="online-resume-title">在线简历</text>
                    </view>
                    <text class="online-resume-desc">点击查看简历详情</text>
                    <view class="online-resume-action">
                      <text class="action-text">查看简历</text>
                      <image class="action-arrow" src="/static/icons/right-arrow-gray.png"></image>
                    </view>
                  </view>
                </view>
                <text class="message-time">{{ formatMessageTime(message.createTime) }}</text>
              </view>
              <image 
                class="avatar" 
                :src="'/static/images/avatar.png'"
              />
            </template>
          </view>
        </view>
      </view>

      <!-- 占位区域，防止消息被输入框遮挡 -->
      <view class="message-placeholder" id="message-bottom"></view>
    </scroll-view>

    <!-- 录音遮罩层 -->
    <view v-if="isRecording" class="recording-mask">
      <view class="recording-content" :class="{ 'cancel-state': isRecordingCancel }">
        <view class="recording-icon-wrapper">
          <image 
            v-if="!isRecordingCancel" 
            class="recording-icon" 
            src="/static/icons/chat/voice.png"
          ></image>
          <image 
            v-else 
            class="recording-icon cancel-icon" 
            src="/static/icons/chat/close.png"
          ></image>
        </view>
        <text class="recording-text">{{ isRecordingCancel ? '松开取消发送' : '松开发送，上滑取消' }}</text>
        <text class="recording-time">{{ recordingTime }}"</text>
      </view>
    </view>

    <!-- 底部输入区域 -->
    <view class="input-area">
      <view class="input-wrapper">
        <!-- 语音输入按钮 -->
        <view class="voice-btn" @click="toggleVoiceInput">
          <image 
            class="input-icon" 
            :src="isVoiceMode ? '/static/icons/chat/keyboard.png' : '/static/icons/chat/voice.png'"
          />
        </view>

        <!-- 文字输入框 -->
        <view class="text-input-wrapper" v-show="!isVoiceMode">
          <input 
            class="text-input"
            type="text"
            v-model="inputText"
            :placeholder="inputPlaceholder"
            placeholder-class="input-placeholder"
            @focus="onInputFocus"
            @blur="onInputBlur"
            @confirm="sendMessage"
          />
        </view>

        <!-- 语音输入按钮（长按录音） -->
        <view 
          class="voice-input-btn" 
          :class="{ 'recording': isRecording }"
          v-show="isVoiceMode"
          @touchstart="startRecord"
          @touchmove="onRecordMove"
          @touchend="endRecord"
          @touchcancel="cancelRecord"
        >
          <text class="voice-text">{{ voiceButtonText }}</text>
        </view>

        <!-- 右侧按钮组 -->
        <view class="right-buttons">
          <!-- 表情按钮 -->
          <view class="emoji-btn" @click="toggleEmoji">
            <image class="input-icon" src="/static/icons/chat/expression.png" />
          </view>

          <!-- 发送按钮或更多按钮 -->
          <view v-if="inputText.trim()" class="send-btn" @click="sendMessage">
            <text class="send-text">发送</text>
          </view>
          <view v-else class="more-btn" @click="showMore">
            <image class="input-icon" src="/static/icons/chat/more.png" />
          </view>
        </view>
      </view>

      <!-- 表情面板 -->
      <view class="emoji-panel" v-show="showEmojiPanel">
        <view class="emoji-grid">
          <view 
            class="emoji-item"
            v-for="(emoji, index) in emojiList"
            :key="index"
            @click="selectEmoji(emoji)"
          >
            <text class="emoji-text">{{ emoji }}</text>
          </view>
        </view>
      </view>

      <!-- 更多面板 - 求职者版本 -->
      <view class="more-panel" v-show="showMorePanel">
        <view class="more-grid">
          <view class="more-item" @click="selectImage">
            <image class="more-icon" src="/static/icons/chat/pic_send.png" />
            <text class="more-text">图片</text>
          </view>
          <view class="more-item" @click="selectResume">
            <image class="more-icon" src="/static/icons/chat/resume_send.png" />
            <text class="more-text">简历</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { onLoad, onUnload, onShow } from '@dcloudio/uni-app';
import CustomHeader from "@/components/CustomHeader.vue";
import { createCandidateChatSessionApi } from "@/api/chat.js";
import { useChatStore } from "../../stores/modules/chat";
import { useSessionStore } from "../../stores/modules/session";

// 使用 Pinia store
const chatStore = useChatStore();

// 响应式数据
const chatUserName = ref(""); // 聊天对象昵称
const sessionId = ref(""); // 会话ID
const jobId = ref(""); // 职位ID
const hrId = ref(""); // HR ID
const inputText = ref(""); // 输入框文字
const inputPlaceholder = ref("对ta发送消息");
const isVoiceMode = ref(false); // 是否为语音模式
const showEmojiPanel = ref(false); // 显示表情面板
const showMorePanel = ref(false); // 显示更多面板
const scrollTop = ref(0); // 滚动位置
const scrollIntoView = ref(""); // 滚动到指定元素
const voiceButtonText = ref("按住 说话"); // 语音按钮文字
const isRecording = ref(false); // 是否正在录音
const isRecordingCancel = ref(false); // 是否处于取消录音状态
const recordingTime = ref(0); // 录音时长（秒）
const recordingTimer = ref(null); // 录音计时器
const recordStartY = ref(0); // 录音开始时的Y坐标

// 消息列表（模拟数据）
const messageList = ref([
        {
          id: "695494127097217024",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971773007435702273",
          msgType: 10,
          content: {
            text: "你好，我看了您的简历，很符合我们的要求"
          },
          createTime: 1758957926556
        },
        {
          id: "695494127097217025",
          sessionId: "1971803632909803521", 
          senderId: "1971803632909803521", // 这是我发送的消息
          receiveId: "1957428994103259137",
          msgType: 10,
          content: {
            text: "谢谢您的关注，请问这个职位的具体要求是什么？"
          },
          createTime: 1758957986556
        },
        {
          id: "695494127097217026",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971803632909803521",
          msgType: 10,
          content: {
            text: "主要负责前端开发，需要熟悉Vue、React等框架，有3年以上工作经验"
          },
          createTime: 1758958046556
        },
        {
          id: "695494127097217027",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971803632909803521",
          msgType: 12, // 语音消息
          content: {
            audioUrl: "https://example.com/audio1.mp3",
            duration: 15,
            isRead: false
          },
          createTime: 1758958106556
        },
        {
          id: "695494127097217028",
          sessionId: "1971803632909803521",
          senderId: "1971803632909803521", // 我发送的语音消息
          receiveId: "1957428994103259137",
          msgType: 12, // 语音消息
          content: {
            audioUrl: "https://example.com/audio2.mp3",
            duration: 8,
            isRead: true
          },
          createTime: 1758958166556
        },
        {
          id: "695494127097217029",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971803632909803521",
          msgType: 11, // 图片消息
          content: {
            imageUrl: "https://picsum.photos/400/300?random=1",
            width: 400,
            height: 300
          },
          createTime: 1758958226556
        },
        {
          id: "695494127097217030",
          sessionId: "1971803632909803521",
          senderId: "1971803632909803521", // 我发送的图片消息
          receiveId: "1957428994103259137",
          msgType: 11, // 图片消息
          content: {
            imageUrl: "https://picsum.photos/350/250?random=2",
            width: 350,
            height: 250
          },
          createTime: 1758958286556
        },
        {
          id: "695494127097217031",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971803632909803521",
          msgType: 11, // 图片消息
          content: {
            imageUrl: "https://picsum.photos/450/350?random=3",
            width: 450,
            height: 350
          },
          createTime: 1758958346556
        },
        {
          id: "695494127097217032",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137",
          receiveId: "1971803632909803521",
          msgType: 16, // 职位卡片消息
          content: {
            beginSalary: 1,
            city: "重庆",
            companyId: "1957432013796626434",
            companyName: "智鑫新能源",
            edu: "大专",
            endSalary: 2,
            expYears: "0-2年",
            face: "http://192.168.56.107:9000/jwcb-hire/user/73ea1e09-3fd7-4a66-9817-22dca26960d7.png",
            financStage: "自有资金",
            jobId: "J020",
            jobName: "行政专员",
            monthlySalary: 13,
            name: "魏灿斌",
            peopleSize: "counts500_999",
            position: "HR经理",
            tags: "行政,后勤,办公",
            userId: "1957428994103259137"
          },
          createTime: 1758958406556
        },
        {
          id: "695494127097217033",
          sessionId: "1971803632909803521",
          senderId: "1971803632909803521", // 我发送的简历消息
          receiveId: "1957428994103259137",
          msgType: 17, // 简历附件消息
          content: {
            id: 123,
            userId: "1971803632909803521",
            fileName: "张三_前端开发工程师_简历.pdf",
            fileSizeMb: 2.5,
            fileType: "pdf",
            fileUrl: "https://example.com/resume/zhangsan_resume.pdf"
          },
          createTime: 1758958466556
        },
        {
          id: "695494127097217034",
          sessionId: "1971803632909803521",
          senderId: "1971803632909803521", // 我发送的另一份简历
          receiveId: "1957428994103259137",
          msgType: 17, // 简历附件消息
          content: {
            id: 124,
            userId: "1971803632909803521",
            fileName: "个人作品集.docx",
            fileSizeMb: 5.2,
            fileType: "docx",
            fileUrl: "https://example.com/resume/portfolio.docx"
          },
          createTime: 1758958526556
        },
        {
          id: "695494127097217035",
          sessionId: "1971803632909803521",
          senderId: "1957428994103259137", // HR发送的面试邀请
          receiveId: "1971803632909803521",
          msgType: 14, // 面试邀请消息
          content: {
            interviewId: "1204361ad12b3519e3bfae0427bed53d"
          },
          createTime: 1758958586556
        },
        {
          id: "695494127097217036",
          sessionId: "1971803632909803521",
          senderId: "1971803632909803521", // 我发送的在线简历
          receiveId: "1957428994103259137",
          msgType: 18, // 在线简历消息
          content: {
            resumeId: "1957428994518528002"
          },
          createTime: 1758958646556
        }
]);

// 用户信息
const currentUserId = ref(""); // 从userStore中获取

// 表情列表
const emojiList = ref([
  "😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣",
  "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "🥰",
  "😘", "😗", "😙", "😚", "😋", "😛", "😝", "😜",
  "🤪", "🤨", "🧐", "🤓", "😎", "🤩", "🥳", "😏"
]);

// 页面加载时执行
onLoad(async (options) => {
  // 注册发送语音的函数
  chatStore.registerSendVoiceEvent(({tempFilePath, duration}) => {
    console.log("=== 求职者聊天页面 - 录音完成 ===");
    console.log("临时文件路径:", tempFilePath);
    console.log("录音时长(秒):", duration);
    console.log("================================");
    
    // TODO: 这里将来要实现实际的发送逻辑
    // 1. 将录音文件上传到服务器
    // 2. 创建语音消息对象
    // 3. 添加到消息列表
    // 4. 通过 WebSocket 发送给对方
  });
  
  // 监听全局事件，用于接收附件消息
  uni.$on('addAttachmentMessage', (message) => {
    console.log("通过全局事件接收到附件消息:", message);
    addAttachmentMessage(message);
  });
  
  console.log("求职者聊天页面参数:", options);
  // 确保中文参数正确显示，如果需要可以进行解码
  chatUserName.value = decodeURIComponent(options.name || "HR");
  sessionId.value = options.sessionId || "";
  jobId.value = options.jobId || "";
  hrId.value = options.hrId || "";
  
  // 创建或获取会话（如果已存在则返回已有会话）
  if (hrId.value && jobId.value) {
    try {
      console.log("创建/获取会话，hrId:", hrId.value, "jobId:", jobId.value);
      const sessionData = await createCandidateChatSessionApi(hrId.value, jobId.value);
      console.log("会话数据:", sessionData);
      
      // 更新 sessionId
      if (sessionData && sessionData.id) {
        sessionId.value = sessionData.id;
      }
      
      // 将会话添加到本地存储
      const sessionStore = useSessionStore();
      sessionStore.upsertSession(sessionData);
    } catch (error) {
      console.error("创建/获取会话失败:", error);
    }
  }
  inputPlaceholder.value = `对${chatUserName.value}发送消息`;
  
  // 从本地存储获取当前用户ID
  try {
    const userInfo = uni.getStorageSync('userInfo');
    console.log("从本地存储获取的userInfo:", userInfo);
    
    if (userInfo && userInfo.id) {
      currentUserId.value = userInfo.id;
    } else {
      // 如果本地存储中没有用户信息，使用默认值用于测试
      currentUserId.value = "1971803632909803521";
    }
  } catch (error) {
    console.error("获取用户信息出错:", error);
    // 使用默认值用于测试
    currentUserId.value = "1971803632909803521";
  }
  
  console.log("当前用户ID:", currentUserId.value);
  
  // 如果有hrId和jobId但没有sessionId，创建会话
  if (hrId.value && jobId.value && !sessionId.value) {
    createChatSession();
  }
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });
});

// 方法定义
// 创建聊天会话
const createChatSession = async () => {
  if (!hrId.value || !jobId.value) {
    console.error("缺少hrId或jobId，无法创建会话");
    return;
  }
  
  try {
    console.log("开始创建聊天会话，hrId:", hrId.value, "jobId:", jobId.value);
    
    const response = await createCandidateChatSessionApi(hrId.value, jobId.value);
    
    console.log("聊天会话创建响应:", response);
    
    if (response && response.id) {
      sessionId.value = response.id;
      console.log("会话创建成功，sessionId:", sessionId.value);
    } else {
      console.error("会话创建失败，响应无效:", response);
    }
  } catch (error) {
    console.error("创建聊天会话出错:", error);
    uni.showToast({
      title: "创建聊天会话失败",
      icon: "none",
      duration: 2000
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 切换语音输入模式
const toggleVoiceInput = () => {
  isVoiceMode.value = !isVoiceMode.value;
  showEmojiPanel.value = false;
  showMorePanel.value = false;
};

// 切换表情面板
const toggleEmoji = () => {
  showEmojiPanel.value = !showEmojiPanel.value;
  showMorePanel.value = false;
  isVoiceMode.value = false;
};

// 显示更多面板
const showMore = () => {
  showMorePanel.value = !showMorePanel.value;
  showEmojiPanel.value = false;
  isVoiceMode.value = false;
};

// 输入框获得焦点
const onInputFocus = () => {
  showEmojiPanel.value = false;
  showMorePanel.value = false;
  // 延迟滚动，确保键盘弹出后再执行
  setTimeout(() => {
    scrollToBottom();
  }, 500);
};

// 输入框失去焦点
const onInputBlur = () => {
  // 可以在这里处理一些逻辑
};

// 判断是否为我发送的消息
const isMyMessage = (message) => {
  return message.senderId === currentUserId.value;
};

// 格式化消息时间
const formatMessageTime = (timestamp) => {
  const date = new Date(timestamp);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 发送消息
const sendMessage = () => {
  if (!inputText.value.trim()) return;
  
  const message = {
    id: Date.now().toString(),
    sessionId: sessionId.value,
    senderId: currentUserId.value,
    receiveId: "", // 接收者ID，需要根据实际情况设置
    msgType: 10,
    content: {
      text: inputText.value.trim()
    },
    createTime: Date.now()
  };
  
  messageList.value.push(message);
  inputText.value = "";
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // TODO: 发送消息到服务器
  console.log("发送消息:", message);
};

// 选择表情
const selectEmoji = (emoji) => {
  inputText.value += emoji;
};

// 开始录音
const startRecord = (e) => {
  isRecording.value = true;
  isRecordingCancel.value = false;
  recordingTime.value = 0;
  voiceButtonText.value = "松开 发送";
  recordStartY.value = e.touches[0].clientY;
  
  // 开始计时
  recordingTimer.value = setInterval(() => {
    recordingTime.value++;
  }, 1000);
  
  // 开始录音
  chatStore.recorder.start({
    duration: 60000, // 最长录音时间60秒
    sampleRate: 44100, // 采样率
    numberOfChannels: 1, // 录音通道数
    encodeBitRate: 192000, // 编码码率
    format: 'mp3', // 音频格式，选择mp3
  });
  console.log("开始录音...");
};

// 录音过程中手指移动
const onRecordMove = (e) => {
  if (!isRecording.value) return;
  
  const currentY = e.touches[0].clientY;
  const deltaY = recordStartY.value - currentY;
  
  // 上滑超过100rpx（约50px）则进入取消状态
  if (deltaY > 50) {
    if (!isRecordingCancel.value) {
      isRecordingCancel.value = true;
      voiceButtonText.value = "松开 取消";
      // 震动反馈
      uni.vibrateShort({
        type: 'light'
      });
    }
  } else {
    if (isRecordingCancel.value) {
      isRecordingCancel.value = false;
      voiceButtonText.value = "松开 发送";
    }
  }
};

// 结束录音
const endRecord = () => {
  // 清除计时器
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value);
    recordingTimer.value = null;
  }
  
  if (isRecordingCancel.value) {
    // 取消发送 - 不调用stop，录音会被丢弃
    console.log("用户取消录音");
    // 停止录音但不触发发送
    chatStore.recorder.stop();
    uni.showToast({
      title: '已取消',
      icon: 'none',
      duration: 1000
    });
  } else {
    // 正常结束录音
    console.log("结束录音，时长:", recordingTime.value + "秒");
    
    // 录音时长太短提示（实际检测在 store 的 onStop 中）
    if (recordingTime.value < 1) {
      chatStore.recorder.stop(); // 也要停止录音
      uni.showToast({
        title: '录音时间太短',
        icon: 'none',
        duration: 1500
      });
    } else {
      // 停止录音，会触发 onStop 回调，然后调用 sendVoice
      chatStore.recorder.stop();
    }
  }
  
  // 重置状态
  isRecording.value = false;
  isRecordingCancel.value = false;
  recordingTime.value = 0;
  voiceButtonText.value = "按住 说话";
};

// 取消录音（touchcancel事件触发）
const cancelRecord = () => {
  // 清除计时器
  if (recordingTimer.value) {
    clearInterval(recordingTimer.value);
    recordingTimer.value = null;
  }
  
  // 停止录音
  console.log("取消录音（touchcancel）");
  chatStore.recorder.stop();
  
  isRecording.value = false;
  isRecordingCancel.value = false;
  recordingTime.value = 0;
  voiceButtonText.value = "按住 说话";
  
  uni.showToast({
    title: '已取消',
    icon: 'none',
    duration: 1000
  });
};

// 选择图片
const selectImage = () => {
  showMorePanel.value = false;
  
  // 显示选择菜单
  uni.showActionSheet({
    itemList: ['从相册选择', '拍照'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 从相册选择
        chooseImageFromAlbum();
      } else if (res.tapIndex === 1) {
        // 拍照
        chooseImageFromCamera();
      }
    }
  });
};

// 从相册选择图片
const chooseImageFromAlbum = () => {
  uni.chooseImage({
    count: 9, // 最多选择9张
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success: (res) => {
      console.log('选择图片成功:', res);
      sendImages(res.tempFilePaths);
    },
    fail: (error) => {
      console.error('选择图片失败:', error);
      uni.showToast({
        title: '选择图片失败',
        icon: 'none',
        duration: 2000
      });
    }
  });
};

// 拍照
const chooseImageFromCamera = () => {
  uni.chooseImage({
    count: 1, // 拍照只能一张
    sizeType: ['original', 'compressed'],
    sourceType: ['camera'],
    success: (res) => {
      console.log('拍照成功:', res);
      sendImages(res.tempFilePaths);
    },
    fail: (error) => {
      console.error('拍照失败:', error);
      uni.showToast({
        title: '拍照失败',
        icon: 'none',
        duration: 2000
      });
    }
  });
};

// 发送图片消息
const sendImages = (imagePaths) => {
  if (!imagePaths || imagePaths.length === 0) return;
  
  // 限制最多9张图片
  const paths = imagePaths.slice(0, 9);
  
  paths.forEach((imagePath, index) => {
    // 获取图片信息
    uni.getImageInfo({
      src: imagePath,
      success: (imageInfo) => {
        // 创建图片消息
        const message = {
          id: (Date.now() + index).toString(),
          sessionId: sessionId.value,
          senderId: currentUserId.value,
          receiveId: hrId.value,
          msgType: 11, // 图片消息
          content: {
            imageUrl: imagePath,
            width: Math.min(imageInfo.width, 400), // 限制最大宽度
            height: Math.min(imageInfo.height, 300) // 限制最大高度
          },
          createTime: Date.now() + index
        };
        
        messageList.value.push(message);
        
        // 滚动到底部
        nextTick(() => {
          scrollToBottom();
        });
        
        // TODO: 发送图片到服务器
        console.log("发送图片消息:", message);
      },
      fail: (error) => {
        console.error('获取图片信息失败:', error);
        uni.showToast({
          title: '图片处理失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  });
  
  // 显示发送成功提示
  uni.showToast({
    title: `已发送${paths.length}张图片`,
    icon: 'success',
    duration: 1500
  });
};

// 选择简历 - 求职者专用
const selectResume = () => {
  showMorePanel.value = false;
  
  // 显示选择简历类型的弹窗
  uni.showActionSheet({
    itemList: ['在线简历', '附件简历'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 选择在线简历 - 直接发送
        sendOnlineResume();
      } else if (res.tapIndex === 1) {
        // 选择附件简历 - 跳转到选择页面
        selectAttachmentResume();
      }
    }
  });
};

// 发送在线简历
const sendOnlineResume = () => {
  console.log("发送在线简历");
  
  // 创建在线简历消息
  const message = {
    id: Date.now().toString(),
    sessionId: sessionId.value,
    senderId: currentUserId.value,
    receiveId: hrId.value,
    msgType: 18, // 在线简历消息
    content: {
      resumeId: "1957428994518528002" // 使用固定的简历ID用于测试
    },
    createTime: Date.now()
  };
  
  messageList.value.push(message);
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // TODO: 发送消息到服务器
  console.log("发送在线简历消息:", message);
  
  uni.showToast({
    title: "简历已发送",
    icon: "success",
    duration: 1500
  });
};

// 选择附件简历
const selectAttachmentResume = () => {
  console.log("选择附件简历");
  
  // 跳转到附件简历选择页面
  uni.navigateTo({
    url: `/pages/common/attachmentResumeSelector?sessionId=${sessionId.value}&hrId=${hrId.value}`
  });
};

// 滚动到底部（滚动到占位区域）
const scrollToBottom = () => {
  nextTick(() => {
    // 使用scroll-into-view滚动到底部占位区域
    scrollIntoView.value = "message-bottom";
    // 同时设置scrollTop确保滚动
    scrollTop.value = 99999;
    // 清除scroll-into-view以便下次使用
    setTimeout(() => {
      scrollIntoView.value = "";
    }, 100);
  });
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 预览图片
const previewImage = (imageUrl) => {
  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl
  });
};

// 跳转到职位详情
const goToJobDetail = (jobId) => {
  console.log("跳转到职位详情，jobId:", jobId);
  uni.navigateTo({
    url: `/pages/candidate/position/positionDetail?jobId=${jobId}`,
  });
};

// 格式化薪资显示
const formatSalary = (job) => {
  if (job.beginSalary && job.endSalary) {
    return `${job.beginSalary}-${job.endSalary}K`;
  }
  return "面议";
};

// 格式化公司规模
const formatPeopleSize = (peopleSize) => {
  if (!peopleSize) return "";
  
  // 硬编码的映射（作为后备方案）
  const sizeMap = {
    counts0_50: "0-50人",
    counts50_100: "50-100人",
    counts100_500: "100-500人",
    counts500_999: "500-999人",
    counts1000_9999: "1000-9999人",
    counts10000: "10000人以上",
  };
  
  return sizeMap[peopleSize] || peopleSize;
};

// 获取前N个标签
const getTopTags = (tags, count) => {
  if (!tags) return [];
  const tagArray = tags.split(",");
  return tagArray.slice(0, count);
};

// 根据文件类型获取简历图标
const getResumeIcon = (fileType) => {
  const base = '/static/icons/candidate/';
  switch (fileType.toLowerCase()) {
    case 'pdf':
      return base + 'pdf.png';
    case 'doc':
      return base + 'doc.png';
    case 'docx':
      return base + 'docx.png';
    case 'png':
      return base + 'PNG.png';
    case 'jpg':
    case 'jpeg':
      return base + 'jpg.png';
    default:
      return base + 'file.png'; // 未知类型使用默认图标
  }
};

// 格式化简历文件大小
const formatResumeSize = (sizeMb) => {
  if (!sizeMb) return '0 MB';
  if (sizeMb < 1) {
    return (sizeMb * 1024).toFixed(0) + ' KB';
  }
  return sizeMb.toFixed(1) + ' MB';
};

// 预览简历文件
const previewResume = (resumeContent) => {
  console.log('点击预览简历:', resumeContent);
  
  if (!resumeContent || !resumeContent.fileUrl) {
    uni.showToast({
      title: "简历文件链接无效",
      icon: "none",
      duration: 2000
    });
    return;
  }

  const fileType = resumeContent.fileType.toLowerCase();
  const fileName = resumeContent.fileName;

  // 跳转到文件预览页面
  uni.navigateTo({
    url: `/pages/common/filePreview?fileUrl=${encodeURIComponent(resumeContent.fileUrl)}&fileName=${encodeURIComponent(fileName)}&fileType=${fileType}`
  });
};

// 查看面试详情
const viewInterviewDetail = (interviewId) => {
  console.log('查看面试详情，interviewId:', interviewId);
  uni.navigateTo({
    url: `/pages/candidate/interview/interviewDetail?interviewId=${interviewId}`
  });
};

// 查看在线简历
const viewOnlineResume = (message) => {
  console.log('查看在线简历，message:', message);
  
  // 判断是否为我发送的消息
  if (isMyMessage(message)) {
    // 求职者查看自己的简历
    uni.navigateTo({
      url: '/pages/candidate/resume/resumePreview'
    });
  } else {
    // 这是从HR收到的简历（理论上不会出现这种情况，因为只有求职者发简历给HR）
    console.warn('候选人收到了在线简历消息，这可能是异常情况');
  }
};

// 添加附件消息到聊天列表（供附件选择页面调用）
const addAttachmentMessage = (messageOrAttachment) => {
  console.log('添加附件消息:', messageOrAttachment);
  
  let message;
  
  // 判断传入的是完整的消息对象还是附件对象
  if (messageOrAttachment.msgType && messageOrAttachment.content) {
    // 传入的是完整的消息对象，直接使用
    message = messageOrAttachment;
  } else {
    // 传入的是附件对象，需要创建消息对象（向后兼容）
    message = {
      id: Date.now().toString(),
      sessionId: sessionId.value,
      senderId: currentUserId.value,
      receiveId: hrId.value,
      msgType: 17, // 简历附件消息
      content: {
        id: messageOrAttachment.id,
        userId: currentUserId.value,
        fileName: messageOrAttachment.name,
        fileSizeMb: messageOrAttachment.fileSizeMb,
        fileType: messageOrAttachment.fileType,
        fileUrl: messageOrAttachment.url
      },
      createTime: Date.now()
    };
  }
  
  messageList.value.push(message);
  
  nextTick(() => {
    scrollToBottom();
  });
  
  // TODO: 发送消息到服务器
  console.log("发送附件简历消息:", message);
};

// 页面显示时检查待处理的消息
onShow(() => {
  console.log("聊天页面显示，检查待处理的消息");
  
  // 检查全局数据中是否有待处理的附件消息
  const app = getApp();
  if (app.globalData && app.globalData.pendingAttachmentMessage) {
    console.log("发现待处理的附件消息:", app.globalData.pendingAttachmentMessage);
    
    // 添加消息到聊天列表
    addAttachmentMessage(app.globalData.pendingAttachmentMessage);
    
    // 清除待处理的消息
    app.globalData.pendingAttachmentMessage = null;
  }
});

// 页面卸载时移除事件监听
onUnload(() => {
  uni.$off('addAttachmentMessage');
});

// 暴露方法给外部调用
defineExpose({
  addAttachmentMessage
});
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f0f2f5;
}

/* Header样式 */
.chat-header {
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  width: 60rpx;
}

/* 消息区域 */
.message-area {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
}

.message-list {
  min-height: 100%;
}

.message-item {
  margin-bottom: 30rpx;
}

.message-wrapper {
  display: flex;
  gap: 20rpx;
}

.message-right .message-wrapper {
  flex-direction: row-reverse;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  flex-shrink: 0;
}

.message-content {
  max-width: 60%;
  display: flex;
  flex-direction: column;
  background-color: transparent;
}

.message-right .message-content {
  align-items: flex-end;
}

.message-bubble {
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  margin-bottom: 8rpx;
  word-wrap: break-word;
  word-break: break-all;
}

.message-bubble-left {
  background-color: #ffffff;
  border-top-left-radius: 4rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.message-bubble-right {
  background-color: #00bdb4;
  border-top-right-radius: 4rpx;
}

.message-text {
  font-size: 32rpx;
  line-height: 1.4;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.message-bubble-right .message-text {
  color: #ffffff;
}

.message-time {
  font-size: 22rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 图片消息样式 */
.image-message-wrapper {
  display: flex;
  align-items: flex-end;
  position: relative;
}

.image-message-wrapper-right {
  justify-content: flex-end;
}

.message-image {
  border-radius: 12rpx;
  max-width: 100%;
  cursor: pointer;
  transition: opacity 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.message-image:active {
  opacity: 0.8;
}

/* 语音消息样式 */
.voice-message {
  min-width: 200rpx;
  max-width: 400rpx;
}

.voice-message-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 8rpx;
  position: relative;
}

.voice-message-wrapper-right {
  flex-direction: row-reverse;
}

.voice-content {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 8rpx 0;
}

.voice-content-right {
  flex-direction: row-reverse;
}

.voice-icon {
  width: 32rpx;
  height: 32rpx;
  flex-shrink: 0;
}

.voice-duration {
  font-size: 28rpx;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.message-bubble-right .voice-duration {
  color: #ffffff;
}

.unread-dot-outside {
  width: 16rpx;
  height: 16rpx;
  flex-shrink: 0;
  margin-bottom: 8rpx;
}

.message-placeholder {
  height: 100rpx;
}

/* 输入区域 */
.input-area {
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  padding: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
  min-height: 80rpx;
}

.voice-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 40rpx;
}

.input-icon {
  width: 48rpx;
  height: 48rpx;
}

.text-input-wrapper {
  flex: 1;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  padding: 0 30rpx;
  min-height: 80rpx;
  display: flex;
  align-items: center;
}

.text-input {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.input-placeholder {
  color: #999;
}

.voice-input-btn {
  flex: 1;
  height: 80rpx;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
}

.voice-input-btn.recording {
  background-color: #e0e0e0;
}

.voice-text {
  font-size: 32rpx;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 录音遮罩层 */
.recording-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.recording-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 80rpx;
  background-color: rgba(0, 0, 0, 0.8);
  border-radius: 24rpx;
  transition: all 0.2s ease;
}

.recording-content.cancel-state {
  background-color: rgba(255, 71, 87, 0.9);
}

.recording-icon-wrapper {
  width: 120rpx;
  height: 120rpx;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.recording-icon {
  width: 60rpx;
  height: 60rpx;
}

.cancel-icon {
  width: 50rpx;
  height: 50rpx;
}

.recording-text {
  font-size: 28rpx;
  color: #ffffff;
  margin-bottom: 16rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.recording-time {
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.right-buttons {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.emoji-btn,
.more-btn {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 40rpx;
}

.send-btn {
  background-color: #00bdb4;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 表情面板 */
.emoji-panel {
  margin-top: 20rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 30rpx;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 20rpx;
}

.emoji-item {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
  border-radius: 12rpx;
}

.emoji-text {
  font-size: 40rpx;
}

/* 更多面板 */
.more-panel {
  margin-top: 20rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 30rpx;
}

.more-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 40rpx;
}

.more-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
}

.more-icon {
  width: 60rpx;
  height: 60rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 10rpx;
}

.more-text {
  font-size: 24rpx;
  color: #666;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

uni-scroll-view{
  width: 95%;
}
scroll-view ::-webkit-scrollbar {
	width: 0;
	height: 0;
	background-color: transparent;
}
.message-right{
    justify-content: flex-end;
}

/* 职位卡片消息样式 */
.job-card-message-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin: 20rpx 0;
}

.job-card-tip {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
  text-align: center;
}

.job-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  width: 90%;
  max-width: 600rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.2s ease;
}

.job-card:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.job-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
  flex: 1;
  margin-right: 20rpx;
}

.job-salary {
  font-size: 30rpx;
  font-weight: 600;
  color: #00bdb4;
}

.company-info {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.company-name {
  font-size: 26rpx;
  color: #666666;
  margin-right: 8rpx;
}

.separator {
  font-size: 26rpx;
  color: #999999;
  margin: 0 8rpx;
}

.company-detail {
  font-size: 26rpx;
  color: #999999;
}

.job-nature {
  display: flex;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.nature-tag {
  font-size: 24rpx;
  color: #666666;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.job-tag {
  font-size: 24rpx;
  color: #999999;
  background-color: #f5f5f5;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hr-info {
  display: flex;
  align-items: center;
}

.hr-avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  margin-right: 12rpx;
}

.hr-text {
  display: flex;
  align-items: center;
}

.hr-name {
  font-size: 26rpx;
  color: #999999;
}

.hr-position {
  font-size: 26rpx;
  color: #999999;
  margin-left: 4rpx;
}

.job-city {
  font-size: 26rpx;
  color: #999999;
}

/* 简历附件消息样式 */
.resume-message-wrapper {
  display: flex;
  align-items: flex-end;
  position: relative;
  margin-bottom: 8rpx;
}

.resume-message-wrapper-right {
  justify-content: flex-end;
}

.resume-attachment {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 20rpx;
  max-width: 400rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.resume-message-wrapper-right .resume-attachment {
  background-color: #00bdb4;
}

.resume-attachment:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.resume-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.resume-details {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0; /* 确保文本可以被截断 */
}

.resume-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.resume-message-wrapper-right .resume-name {
  color: #ffffff;
}

.resume-size {
  font-size: 24rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.resume-message-wrapper-right .resume-size {
  color: rgba(255, 255, 255, 0.8);
}

/* 面试邀请消息样式 */
.interview-message-wrapper {
  display: flex;
  align-items: flex-end;
  position: relative;
  margin-bottom: 8rpx;
}

.interview-message-wrapper-right {
  justify-content: flex-end;
}

.interview-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  max-width: 400rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.interview-message-wrapper-right .interview-card {
  background-color: #00bdb4;
}

.interview-card:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.interview-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.interview-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.interview-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.interview-message-wrapper-right .interview-title {
  color: #ffffff;
}

.interview-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  line-height: 1.4;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.interview-message-wrapper-right .interview-desc {
  color: rgba(255, 255, 255, 0.9);
}

.interview-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.action-text {
  font-size: 26rpx;
  color: #999;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.interview-message-wrapper-right .action-text {
  color: rgba(255, 255, 255, 0.8);
}

.action-arrow {
  width: 20rpx;
  height: 20rpx;
  flex-shrink: 0;
}

/* 在线简历消息样式 */
.online-resume-message-wrapper {
  display: flex;
  align-items: flex-end;
  position: relative;
  margin-bottom: 8rpx;
}

.online-resume-message-wrapper-right {
  justify-content: flex-end;
}

.online-resume-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  max-width: 400rpx;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-left: 4rpx solid #00bdb4;
}

.online-resume-message-wrapper-right .online-resume-card {
  background-color: #00bdb4;
  border-left: 4rpx solid #ffffff;
}

.online-resume-card:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.online-resume-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.online-resume-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.online-resume-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.online-resume-message-wrapper-right .online-resume-title {
  color: #ffffff;
}

.online-resume-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  line-height: 1.4;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.online-resume-message-wrapper-right .online-resume-desc {
  color: rgba(255, 255, 255, 0.9);
}

.online-resume-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
